import { ref, onUnmounted } from 'vue';
import HSUploader from '../uploader/index.js';

export function useRecorder(onStopCallback) {
  const mediaRecorder = ref(null);
  const audioChunks = ref([]);
  const isRecording = ref(false);
  const sliceTime = 300;

  const startRecording = async () => {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      // 没法模拟https环境，本地环境模拟，上线删掉:
      isRecording.value = true;
      // console.error('getUserMedia not supported on your browser!');
      return;
    }
    
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      isRecording.value = true;
      mediaRecorder.value = new MediaRecorder(stream);
  
      mediaRecorder.value.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunks.value.push(event.data);
        }
      };
  
      mediaRecorder.value.onstop = async () => {
        const audioBlob = new Blob(audioChunks.value, { type: mediaRecorder.value.mimeType });
        const audioUrl = URL.createObjectURL(audioBlob);
        // 释放内存
        URL.revokeObjectURL(audioUrl);
      };
  
      mediaRecorder.value.start(sliceTime);
    } catch (err) {
      console.error('Could not start recording:', err);
    }
  };

  const uploadedCallback = (url) => {
    if (onStopCallback) {
      onStopCallback(url);
    }
  }

  const uploadFile = async () => {
    const uploader = new HSUploader();
    const blob = new Blob(audioChunks.value, { type: mediaRecorder.value.mimeType });
    await uploader.upload(blob, uploadedCallback);
  };

  const pauseRecording = () => {
    if (mediaRecorder.value) {
      mediaRecorder.value.stop();
      isRecording.value = false;
    }
  };

  const stopRecording = async () => {
    if (mediaRecorder.value) {
      mediaRecorder.value.stop();
      isRecording.value = false;
      await uploadFile();
      audioChunks.value = [];
    } else {
      // 没法模拟https环境，本地环境模拟，上线删掉:
      const fakeUrl = 'https://clinic-voice-1319532402.cos.ap-beijing.myqcloud.com/hs-uploads/web/a83d3d94-1ba6-40c9-afb6-bc8ca146e041';
      isRecording.value = false;
      onStopCallback(fakeUrl);
    }
  };

  const getRecordedFile = () => {
    if (audioChunks.value.length) {
      return new Blob(audioChunks.value, { type: mediaRecorder.value.mimeType });
    }
    return null;
  };

  onUnmounted(() => {
    if (mediaRecorder.value) {
      isRecording.value = false;
      mediaRecorder.value.stream.getTracks().forEach(track => track.stop());
    }
  });

  return {
    startRecording,
    pauseRecording,
    stopRecording,
    getRecordedFile,
    isRecording: isRecording
  };
}